<!-- Created by henian.xu on 2018/8/30. -->

<template>
    <form 
        class="form"
        :class="classes"
        :autocomplete="autocomplete">
        <slot/>
    </form>
</template>

<script>
export default {
    name: 'XForm',
    componentName: 'XForm',
    provide() {
        return { xForm: this };
    },
    data() {
        return {
            fields: [],
        };
    },
    props: {
        models: {
            type: Object,
            default() {
                return {};
            },
        },
        rules: {
            type: Object,
            default() {
                return {};
            },
        },
        border: {
            type: Boolean,
            default: false,
        },
        autocomplete: {
            type: Boolean,
            default: false,
        },
        feedback: {
            type: Boolean,
            default: false,
        },
    },
    computed: {
        classes() {
            const { border } = this;
            return [{ border }];
        },
    },
    methods: {
        validate() {
            if (!this.models) {
                throw new Error('[Form]model is required for validate to work!');
            }
            let callback,
                count = 0,
                valid = true;

            const len = this.fields.length,
                promise = new Promise((resolve, reject) => {
                    callback = () => {
                        if (!len || ++count === len) {
                            valid ? resolve(valid) : reject(valid);
                        }
                    };
                });

            if (!len) callback();

            this.fields.forEach(field => {
                field
                    .validate()
                    .then(() => {
                        callback();
                    })
                    .catch(() => {
                        valid = false;
                        callback();
                    });
            });

            return promise;
        },
        addField(field) {
            if (!field || !field._isVue) return;
            this.fields.push(field);
        },
        removeField(field) {
            if (!field || !field._isVue) return;
            const index = this.fields.indexOf(field);
            if (index !== -1) this.fields.splice(index, 1);
        },
    },
};
</script>

<style lang="scss">
.form {
    &.border {
        border: solid $color-border;
        border-width: 1px 0;
    }
}
</style>
